package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressMapper;
import com.sky.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;
    @Override
    public void addAddress(AddressBook addressBook) {

        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        addressBook.setIsDefault(0);
        addressMapper.addAddress(addressBook);
    }

    @Override
    public List<AddressBook> getAllAddress() {
        Long userId = BaseContext.getCurrentId();
        AddressBook addressBook = AddressBook.builder()
                .userId(userId)
                .build();
        List<AddressBook> list =  addressMapper.getAllAddress(addressBook);

        return list;
    }

    @Override
    @Transactional
    public void setDefaultAddress(AddressBook addressBook) {
        //将所有的地址都设置为不是默认地址
        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        addressBook.setIsDefault(0);
        addressMapper.setDefaultAddress(addressBook);

        //将这个地址设置为默认地址  1
        addressBook.setIsDefault(1);
        addressMapper.update(addressBook);
    }

    @Override
    public AddressBook echo(Long id) {
        AddressBook addressBook = AddressBook.builder().id(id).build();
        List<AddressBook> allAddress = addressMapper.getAllAddress(addressBook);

        return  allAddress.get(0);
    }

    @Override
    public void update(AddressBook addressBook) {
        addressMapper.update(addressBook);
    }

    @Override
    public void deleteById(Long id) {
        addressMapper.delete(id);
    }

    @Override
    public AddressBook getDefault() {
        AddressBook addressBook = AddressBook.builder()
                .userId(BaseContext.getCurrentId())
                .isDefault(1)
                .build();
        List<AddressBook> allAddress = addressMapper.getAllAddress(addressBook);
        return allAddress.get(0);
    }

}
